# -*- coding: utf-8 -*-
import os
import shutil
import configparser
import sys

cnf_file = "myback.ini"
config = configparser.ConfigParser()
config.read(cnf_file)

slave_container_inner_data_path = config.get("slave", "slave_container_inner_data_path")
inner_backup_dir = config.get("myback", "inner_backup_dir")
backupfilelist = os.path.join(inner_backup_dir, "backupfilelist.log")
stop_at = stop_at  = sys.argv[1]
cnf_file = "/myback/my.cnf"
inner_work_dir = config.get("myback", "inner_work_dir")


# 返回备份日志中的最新的一个早于stop_at时间的完整备份，以及其后面的增量备份
def get_restorefile_list():
    list_backup = []
    list_restore_file = []
    if os.path.exists(backupfilelist):
        with open(backupfilelist, 'r') as f:
            lines = f.readlines()
            for line in lines:
                list_backup.append(line.replace("\n", ""))
    if (list_backup):
        for i in range(len(list_backup) - 1, -1, -1):
            list_restore_file.append(list_backup[i])
            backup_name = list_backup[i].split("|")[2]
            if "full" in backup_name:
                full_backup_time = list_backup[i].split("|")[1]
                if (stop_at < full_backup_time):
                    break
                else:
                    list_restore_file = None
    # restore file in the list_restore_log
    list_restore_file.reverse()
    return list_restore_file


def restore_backup_data():
    list_restore_backup = get_restorefile_list()
    full_restore_path = inner_work_dir + list_restore_backup[0].split("|")[-1].replace(".xbstream", "")
    print("innobackupex --defaults-file={0} --datadir={1} --copy-back --rsync {2}".format(cnf_file,
                                                                                          slave_container_inner_data_path,
                                                                                          full_restore_path))
    os.system("innobackupex --defaults-file={0} --datadir={1} --copy-back --rsync {2}".format(cnf_file,
                                                                                              slave_container_inner_data_path,
                                                                                              full_restore_path))
    # 清除掉解压的备份
    # clean_expired_file()


def clean_expired_file():
    for backup_name in os.listdir(inner_work_dir):
        if os.path.isdir(backup_name):
            shutil.rmtree(os.path.join(inner_work_dir, backup_name))


if __name__ == '__main__':
    restore_backup_data()
